<template>
  <div class="py-3" style="mix-width: 1050px; overflow-x: auto">
    <div class="report-action">
      <!-- <el-button type="primary"
                 @click="$router.back()"><i class="fa fa-angle-left"></i>
        返回</el-button> -->
      <el-button type="primary" @click="printPage" :loading="printLoading">
        <i class="fa fa-print"></i>
        打印
      </el-button>
      <el-button
        type="primary"
        :disabled="isComplete"
        @click="onReportComplete"
        v-show="!viewMode"
        :loading="addLoading"
      >
        <i class="fa fa-save"></i>
        &nbsp;
        <span>{{ isComplete ? '评级结果已完成' : '完成评级结果' }}</span>
      </el-button>
    </div>
    <div class="report-wrap" v-loading="loading">
      <div class="report-main" id="report-print" :class="{ 'report-complete': isComplete }">
        <h2 class="report-title">
          {{ dataBase.customer_name }}
          <br />
          <span>“铜农易贷”信用评级报告</span>
        </h2>

        <div class="text-right font-weight-bold">
          项目编号：
          <span v-if="dataReport.rating_number">{{ dataReport.rating_number }}</span>
          <span v-else class="d-print-none">
            <el-tooltip
              class="item"
              effect="dark"
              content="评级结果完成后，项目编号自动生成"
              placement="bottom"
            >
              <el-button type="text" class="text-muted">
                待定
                <i class="fa fa-question-circle"></i>
              </el-button>
            </el-tooltip>
          </span>
        </div>

        <div class="report-section">
          <h3 class="report-section-title">
            一、基本信息
            <a name="banned_result"></a>
          </h3>
          <table class="table table-bordered">
            <colgroup>
              <col width="17%" />
              <col width="17%" />
              <col width="12%" />
              <col width="22%" />
              <col width="15%" />
              <col width="18%" />
            </colgroup>
            <tbody>
              <tr>
                <td>企业名称</td>
                <td colspan="3" class="text-left">{{ dataBase.customer_name }}</td>
                <td>成立日期</td>
                <td>{{ $utils.dateFormat(dataBaseInfo.established_date, 'yyyy.MM.dd') }}</td>
              </tr>
              <tr>
                <td>产业类型</td>
                <td colspan="2">{{ enumFarmType[dataBase.farm_type] }}</td>
                <td>产业规模</td>
                <td>{{ dataBaseIndustrial.scale }}</td>
                <td>单位：{{ dataBaseIndustrial.uscale || '' }}</td>
              </tr>
              <tr>
                <td>经营年限</td>
                <td>{{ dataBaseInfo.bussiness_years }}年</td>
                <td>统一信用代码</td>
                <td colspan="3">{{ dataBase.register_no }}</td>
              </tr>
              <tr>
                <td>经营地址</td>
                <td colspan="3">{{ dataBase.address }}</td>
                <td>贷款用途</td>
                <td>{{ dataBase.funds_use_dir }}</td>
              </tr>
              <tr>
                <td>已投金额</td>
                <td>{{ dataBase.invest_total || 0 }}万元</td>
                <td>申请贷款金额</td>
                <td>{{ dataBase.apply_funds || 0 }}万元</td>
                <td>负债金额</td>
                <td>{{ dataBase.en_debt || 0 }}万元</td>
              </tr>
              <tr>
                <td>法人姓名</td>
                <td>{{ dataBase.corp_name }}</td>
                <td>联系电话</td>
                <td>{{ dataBase.mobile_no }}</td>
                <td>户籍地址</td>
                <td>{{ dataBaseSh.address }}</td>
              </tr>
            </tbody>
          </table>

          <h3 class="report-section-title">二、禁入指标</h3>
          <table class="table table-bordered">
            <colgroup>
              <col width="17%" />
              <col width="17%" />
              <col width="12%" />
              <col width="22%" />
              <col width="15%" />
              <col width="18%" />
            </colgroup>
            <tbody>
              <tr>
                <td rowspan="3">禁入指标情况</td>
                <td colspan="3" class="text-left report-input-last-td" width="51%">
                  1. 被评主体或其实际控制人有赌博、吸毒、酗酒等不良嗜好的
                </td>
                <td rowspan="3" colspan="2" class="text-left report-input-td">
                  <span v-if="!isSuperEdit && !issuperEdit">
                    {{ dataReportSolid.banned_result }}
                  </span>
                  <textarea
                    v-else
                    type="text"
                    class="form-control d-print-none"
                    v-model="dataReport.banned_result"
                    rows="4"
                    wrap="hard"
                    placeholder="请填写结论"
                    ref="textarea_banned_result"
                    @blur="onReportSave('banned_result')"
                  ></textarea>
                </td>
              </tr>
              <tr>
                <td colspan="3" class="text-left">
                  2. 被评主体或其实际控制人有挪用担保贷款的不良记录的
                </td>
              </tr>
              <tr>
                <td colspan="3" class="text-left">
                  3. 被评主体未获得生产、经营必备的相关许可证、资质等
                </td>
              </tr>
            </tbody>
          </table>

          <h3 class="report-section-title">三、评分过程</h3>
          <table class="table table-bordered">
            <colgroup>
              <col width="17%" />
              <col width="17%" />
              <col width="12%" />
              <col width="22%" />
              <col width="15%" />
              <col width="18%" />
            </colgroup>
            <tbody>
              <tr>
                <td class="font-weight-bold">一类指标</td>
                <td class="font-weight-bold">二级指标</td>
                <td class="font-weight-bold">指标权重</td>
                <td class="font-weight-bold">数据来源（附件标签）</td>
                <td class="font-weight-bold">
                  被评主体得分
                  <a name="subject_score"></a>
                </td>
                <td class="font-weight-bold">各项加权得分</td>
              </tr>
              <tr v-for="(score, index) in dataScore" :key="index">
                <td v-if="score.rowspan" :rowspan="score.rowspan">
                  {{ score.first_level_norm_name }}（{{ toDecimal2(score.totalScore) }}）
                </td>
                <td class="text-left">{{ score.second_level_norm_name }}</td>
                <td>{{ score.norm_weight }}%</td>
                <td class="text-left">{{ score.data_resource }}</td>
                <!--<td>{{score.subject_score}}</td>-->
                <td class="report-input-td">
                  <span v-if="!isSuperEdit && !issuperEdit">{{ score.subject_score }}</span>
                  <input
                    type="number"
                    class="form-control d-print-none"
                    v-else
                    v-model="score.subject_score"
                    @blur="onScoreSave('subject_score', index)"
                    min="0.00"
                    max="100"
                    step="0.01"
                  />
                </td>
                <td class="bg-light">
                  {{
                    (score.weight_score = ((score.norm_weight * score.subject_score) / 100).toFixed(
                      2
                    ))
                  }}
                </td>
              </tr>
              <tr>
                <td colspan="2"></td>
                <td>100.0%</td>
                <td></td>
                <td></td>
                <td class="font-weight-bold">{{ dataScoreGet }}</td>
              </tr>
              <tr v-for="(score, index) in dataScoreLoseList" :key="score.id">
                <td :rowspan="dataScoreLoseList.length" v-if="!index">扣分项</td>
                <td class="text-left">{{ score.second_level_norm_name }}</td>
                <td></td>
                <td class="text-left">{{ score.data_resource }}</td>
                <td class="report-input-td">
                  <input
                    type="number"
                    class="form-control d-print-none"
                    v-if="isSuperEdit && issuperEdit"
                    v-model="score.subject_score"
                    @blur="onScoreSave('subject_score', index, true)"
                    min="0.00"
                    max="100"
                    step="0.01"
                  />
                  <span v-else>
                    {{ score.subject_score === '0.00' ? '无' : score.subject_score }}
                  </span>
                </td>
                <td class="bg-light">{{ score.weight_score }}</td>
              </tr>
              <tr>
                <td colspan="5" rowspan="2">得分</td>
                <td class="font-weight-bold">{{ dataScoreLose }}</td>
              </tr>
              <tr>
                <td>{{ dataScoreApiGet }}</td>
              </tr>
              <tr>
                <td colspan="5">对应等级</td>
                <td class="font-weight-bold">{{ dataScoreLevel }}</td>
              </tr>
            </tbody>
          </table>

          <h3 class="report-section-title">四、指标分析</h3>
          <p><b>1、一类指标分析</b></p>
          <div style="border: 1px solid #333">
            <img :src="echartsFirstImg" alt="" class="d-none d-print-block w-100" />
            <el-echarts
              :option="optionFirst"
              :width="986"
              class="d-print-none"
              ref="echartsFirst"
            ></el-echarts>
          </div>
          <table class="table table-bordered mt-1">
            <colgroup>
              <col width="17%" />
              <col width="17%" />
              <col width="12%" />
              <col width="22%" />
              <col width="15%" />
              <col width="18%" />
            </colgroup>
            <tbody>
              <tr>
                <td class="font-weight-bold">
                  <a name="first_norm_result"></a>
                  一类指标
                </td>
                <td class="font-weight-bold">一类指标得分占比</td>
                <td class="font-weight-bold">指标得分</td>
                <td class="font-weight-bold">得分高于80</td>
                <td class="font-weight-bold">得分60-79</td>
                <td class="font-weight-bold">得分低于60</td>
              </tr>
              <tr v-for="(item, p) in dataScoreFirstList" :key="p">
                <td>{{ item.name }}</td>
                <td>{{ item.percent }}%</td>
                <td>{{ item.score }}</td>
                <td><span v-show="item.score_a">&radic;</span></td>
                <td><span v-show="item.score_b">&radic;</span></td>
                <td><span v-show="item.score_c">&radic;</span></td>
              </tr>
              <tr>
                <td colspan="3" class="report-input-last-td">结论</td>
                <td colspan="3" class="report-input-td">
                  <span v-if="!isSuperEdit && !issuperEdit">
                    {{ dataReportSolid.first_norm_result }}
                  </span>
                  <textarea
                    v-else
                    type="text"
                    class="form-control d-print-none"
                    v-model="dataReport.first_norm_result"
                    rows="2"
                    wrap="hard"
                    placeholder="请填写结论"
                    ref="textarea_first_norm_result"
                    @blur="onReportSave('first_norm_result')"
                  ></textarea>
                </td>
              </tr>
            </tbody>
          </table>

          <p>
            <b>
              2、二类指标分析
              <a name="second_norm_result"></a>
            </b>
          </p>
          <div style="border: 1px solid #333">
            <img :src="echartsSecondImg" alt="" class="d-none d-print-block w-100" />
            <el-echarts
              :option="optionSecond"
              height="400"
              :width="986"
              class="d-print-none"
              ref="echartsSecond"
            ></el-echarts>
          </div>
          <table class="table table-bordered mt-1">
            <colgroup>
              <col width="17%" />
              <col width="17%" />
              <col width="12%" />
              <col width="22%" />
              <col width="15%" />
              <col width="18%" />
            </colgroup>
            <tbody>
              <tr>
                <td>指标等级</td>
                <td>指标数</td>
                <td>占比</td>
                <td colspan="3">指标结论分析</td>
              </tr>
              <tr v-for="(item, sl) in dataScoreSecondList" :key="sl">
                <td>{{ item.label }}</td>
                <td>{{ item.count }}</td>
                <td>{{ item.percent }}%</td>
                <td v-if="!sl" rowspan="4" colspan="3" class="report-input-td">
                  <span v-if="!isSuperEdit && !issuperEdit">
                    {{ dataReportSolid.second_norm_result }}
                  </span>
                  <textarea
                    v-else
                    type="text"
                    class="form-control d-print-none"
                    v-model="dataReport.second_norm_result"
                    rows="5"
                    wrap="hard"
                    placeholder="请填写结论"
                    ref="textarea_second_norm_result"
                    @blur="onReportSave('second_norm_result')"
                  ></textarea>
                </td>
                <!--<td v-else="!sl" rowspan="4" colspan="3" class="report-input-td">-->
                <!--<span v-if="isComplete">{{dataReportSolid.second_norm_result}}</span>-->
                <!--<textarea v-else type="text" class="form-control d-print-none"-->
                <!--v-model="dataReport.second_norm_result" rows="5" wrap="hard"-->
                <!--placeholder="请填写结论" ref="textarea_second_norm_result" @blur="onReportSave('second_norm_result')"></textarea>-->
                <!--</td>-->
              </tr>
            </tbody>
          </table>

          <p>
            <b>
              3、扣分项分析
              <a name="litigation_des"></a>
            </b>
          </p>
          <table class="table table-bordered">
            <colgroup>
              <col width="17%" />
              <col width="17%" />
              <col width="12%" />
              <col width="22%" />
              <col width="15%" />
              <col width="18%" />
            </colgroup>
            <tbody>
              <tr>
                <td>债务涉诉情况</td>
                <td colspan="5" class="report-input-td">
                  <span v-if="!isSuperEdit && !issuperEdit">
                    {{ dataReportSolid.litigation_des }}
                  </span>
                  <textarea
                    v-else
                    type="text"
                    class="form-control d-print-none"
                    v-model="dataReport.litigation_des"
                    rows="1"
                    wrap="hard"
                    placeholder="请填写债务涉诉情况"
                    ref="textarea_litigation_des"
                    @blur="onReportSave('litigation_des')"
                  ></textarea>
                </td>
              </tr>
              <tr>
                <td rowspan="5">
                  银行征信情况
                  <a name="deduction_result"></a>
                </td>
                <td>主体类型</td>
                <td>贷款余额</td>
                <td>逾期次数</td>
                <td>逾期金额</td>
                <td>最大逾期时长</td>
              </tr>
              <tr>
                <td>企业</td>
                <td>{{ dataCreditCompany.loan_left | textFilter('万元') }}</td>
                <td>{{ dataCreditCompany.overdue_count | textFilter }}</td>
                <td>{{ dataCreditCompany.overdue_amount | textFilter('万元') }}</td>
                <td>{{ dataCreditCompany.max_overdue_days | textFilter('天') }}</td>
              </tr>
              <tr>
                <td>配偶</td>
                <td>{{ dataCreditSpouse.loan_left | textFilter('万元') }}</td>
                <td>{{ dataCreditSpouse.overdue_count | textFilter('万元') }}</td>
                <td>{{ dataCreditSpouse.overdue_amount | textFilter('万元') }}</td>
                <td>{{ dataCreditSpouse.max_overdue_days | textFilter('天') }}</td>
              </tr>
              <tr>
                <td>实际控制人</td>
                <td>{{ dataCreditLegal.loan_left | textFilter('万元') }}</td>
                <td>{{ dataCreditLegal.overdue_count | textFilter }}</td>
                <td>{{ dataCreditLegal.overdue_amount | textFilter('万元') }}</td>
                <td>{{ dataCreditLegal.max_overdue_days | textFilter('天') }}</td>
              </tr>
              <tr>
                <td colspan="5" class="text-left report-input-td">
                  <div style="min-height: 24px" v-if="!isSuperEdit && !issuperEdit">
                    {{ dataReportSolid.deduction_result }}
                  </div>
                  <textarea
                    v-else
                    type="text"
                    class="form-control d-print-none"
                    v-model="dataReport.deduction_result"
                    rows="1"
                    wrap="hard"
                    placeholder="请填写结论"
                    ref="textarea_litigation_des"
                    @blur="onReportSave('deduction_result')"
                  ></textarea>
                </td>
              </tr>
            </tbody>
          </table>

          <h3 class="report-section-title">五、审核意见</h3>
          <table class="table table-bordered">
            <colgroup>
              <col width="17%" />
              <col width="17%" />
              <col width="12%" />
              <col width="22%" />
              <col width="15%" />
              <col width="18%" />
            </colgroup>
            <tbody>
              <tr>
                <td rowspan="2">
                  评级意见
                  <a name="rating_opinion"></a>
                </td>
                <td colspan="5" class="text-left report-input-td">
                  <div style="min-height: 24px" v-if="!isSuperEdit && !issuperEdit">
                    {{ dataReportSolid.rating_opinion }}
                  </div>
                  <textarea
                    v-else
                    type="text"
                    class="form-control d-print-none"
                    v-model="dataReport.rating_opinion"
                    rows="5"
                    wrap="hard"
                    placeholder="请填写评级意见"
                    ref="textarea_rating_opinion"
                    @blur="onReportSave('rating_opinion')"
                  ></textarea>
                </td>
              </tr>
              <tr>
                <td colspan="3" class="text-left">
                  <p>调查人员A签字：</p>
                  <div>日期：</div>
                </td>
                <td colspan="2" class="text-left">
                  <p>调查人员B签字：</p>
                  <div>日期：</div>
                </td>
              </tr>
              <tr>
                <td rowspan="2">
                  担保建议
                  <a name="guarantee_opinion"></a>
                </td>
                <td colspan="5" class="text-left report-input-td">
                  <div style="min-height: 24px" v-if="!isSuperEdit && !issuperEdit">
                    {{ dataReportSolid.guarantee_opinion }}
                  </div>
                  <textarea
                    v-else
                    type="text"
                    class="form-control d-print-none"
                    v-model="dataReport.guarantee_opinion"
                    rows="5"
                    wrap="hard"
                    placeholder="请填写担保建议"
                    ref="textarea_guarantee_opinion"
                    @blur="onReportSave('guarantee_opinion')"
                  ></textarea>
                </td>
              </tr>
              <tr>
                <td colspan="3" class="text-left">
                  <p>负责人签字：</p>
                  <div>评级机构签章：</div>
                </td>
                <td colspan="2" class="text-left">
                  <div>日期：</div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="report-action">
      <!-- <el-button type="primary"
                 @click="$router.back()"><i class="fa fa-angle-left"></i>
        返回</el-button> -->
      <el-button type="primary" @click="printPage" :loading="printLoading">
        <i class="fa fa-print"></i>
        打印
      </el-button>
      <el-button
        type="primary"
        :disabled="isComplete"
        @click="onReportComplete"
        v-show="!viewMode"
        :loading="addLoading"
      >
        <i class="fa fa-save"></i>
        &nbsp;
        <span>{{ isComplete ? '评级结果已完成' : '完成评级结果' }}</span>
      </el-button>
    </div>
  </div>
</template>

<script>
import { printHtml } from '@vimi/utils-tool'
import {
  enumFarmType,
  enumCustomerSource,
  enumDatumCollStatus,
  enumRatingStatus,
} from '@/credit/plugins/enum'
export default {
  components: {},
  props: {
    viewMode: Boolean,
    relatedId: String,
  },
  data() {
    return {
      enumFarmType,
      enumCustomerSource,
      enumDatumCollStatus,
      enumRatingStatus,
      customer_related_id: '',
      loading: false,
      dataBase: {}, // 关联基本信息
      dataBaseInfo: {}, // 企业基本信息
      dataBaseSh: {}, // 法人信息
      dataBaseIndustrial: {}, // 规模信息
      dataScore: [],
      dataScoreEmpty: [],
      dataScoreGet: 0,
      dataScoreApiGet: 0,
      dataScoreLose: 0,
      dataScoreLoseList: [],
      dataScoreLoseListEmpty: [],
      dataScoreLevel: '',
      optionFirst: {},
      echartsFirstImg: '',
      dataScoreFirstList: [],
      optionSecond: {},
      echartsSecondImg: '',
      dataScoreSecondList: [
        { label: '优质（80分以上）', count: 0, percent: 0 },
        { label: '合格（60-79）', count: 0, percent: 0 },
        { label: '劣势（30-59）', count: 0, percent: 0 },
        { label: '极差（0--29）', count: 0, percent: 0 },
      ],
      dataReport: {},
      dataReportSolid: {},
      isAddReport: false,
      addLoading: false,
      dataCreditCompany: {
        loan_left: '',
        overdue_count: '',
        overdue_amount: '',
        max_overdue_days: '',
      },
      dataCreditLegal: {
        loan_left: '',
        overdue_count: '',
        overdue_amount: '',
        max_overdue_days: '',
      },
      dataCreditSpouse: {
        loan_left: '',
        overdue_count: '',
        overdue_amount: '',
        max_overdue_days: '',
      },
      printLoading: false,
      reportData: {},
    }
  },
  computed: {
    isComplete() {
      return this.dataReportSolid.rating_status === '2' || this.viewMode
    },
    isSuper() {
      return this.$store.getters.user.job === 'org_credit_super'
    },
    isSuperEdit() {
      return !this.isComplete
    },
    issuperEdit() {
      return this.isSuper
    },
  },
  watch: {
    relatedId() {
      this.init()
    },
  },
  created() {
    this.init()
  },
  mounted() {},
  methods: {
    init() {
      this.customer_related_id = this.relatedId || this.$route.query.id
      this.getDataBase()
      this.getLevelCustomer()
      this.getLevelScore()
      this.getLevelReport()
    },

    // 关联基本信息
    async getDataBase() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'customer_related_view', {
          index: 1,
          size: 1,
          'customer_related_id.eq': this.customer_related_id,
        })
      )
      this.loading = false
      if (res && res.data && res.data.data && res.data.data.length) {
        this.dataBase = res.data.data[0]
        this.getDataBaseInfo()
        this.getDataBaseSh()
        this.getDataBaseIndustrial()
      } else {
        // return this.$message.error('获取客户信息失败，请重试！')
      }
    },

    // 关联基本信息
    async getDataBaseInfo() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_info', {
          index: 1,
          size: 1,
          'customer_id.eq': this.dataBase.customer_id,
        })
      )
      this.loading = false
      if (res && res.data && res.data.data && res.data.data.length) {
        this.dataBaseInfo = res.data.data[0]
      } else {
        // return this.$message.error('获取客户信息失败，请重试！')
      }
    },

    // 产业规模
    async getDataBaseIndustrial() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(
          'credit',
          'datum_customer_industrial',
          {
            index: 1,
            size: 1,
            'customer_related_id.eq': this.customer_related_id,
          },
          { scale: 'desc' }
        )
      )
      this.loading = false
      if (res && res.data && res.data.data && res.data.data.length) {
        this.dataBaseIndustrial = res.data.data[0]
      }
    },

    // 法人信息
    async getDataBaseSh() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_shareholder_view', {
          'customer_id.eq': this.dataBase.customer_id,
          'service_id.eq': this.dataBase.service_id,
        })
      )
      this.loading = false
      if (res && res.data) {
        for (const rd of res.data) {
          if (rd.is_corp === '1') {
            this.dataBaseSh = rd
            this.dataCreditLegal.shareholder_id = rd.datum_customer_shareholder_id
          } else if (rd.is_corp === '2') {
            this.dataCreditSpouse.shareholder_id = rd.datum_customer_shareholder_id
          }
        }
        this.getCredit()
      }
    },

    // 得分及等级
    async getLevelScore() {
      // this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'credit_level_score', {
          index: 1,
          size: 1,
          'customer_related_id.eq': this.customer_related_id,
        })
      )
      // this.loading = false
      if (res && res.data && res.data.data && res.data.data.length) {
        const data = res.data.data[0]
        this.dataScoreLevel = data.score_level || ''
        this.dataScoreApiGet = data.score || ''
      } else {
        return this.$message.warning('暂无评级得分数据！')
      }
    },

    // 银行征信情况
    async getCredit() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_credit', {
          'customer_related_id.eq': this.customer_related_id,
        })
      )
      this.loading = false

      if (res && res.data) {
        const creditCompany = []
        const creditLegal = []
        const creditSpouse = []
        for (const data of res.data) {
          if (data.customer_id === data.datum_customer_shareholder_id) {
            // 企业
            creditCompany.push(data)
          } else if (data.datum_customer_shareholder_id === this.dataCreditLegal.shareholder_id) {
            // 法人
            creditLegal.push(data)
          } else if (data.datum_customer_shareholder_id === this.dataCreditSpouse.shareholder_id) {
            // 法人的配偶
            creditSpouse.push(data)
          }
        }

        // 余额、次数、金额取总和
        this.dataCreditCompany.loan_left = 0
        this.dataCreditCompany.overdue_count = 0
        this.dataCreditCompany.overdue_amount = 0
        this.dataCreditCompany.max_overdue_days = 0
        for (const cc of creditCompany) {
          const lf = parseFloat(cc.loan_left)
          this.dataCreditCompany.loan_left += isNaN(lf) ? 0 : lf
          const lc = parseFloat(cc.overdue_count)
          this.dataCreditCompany.overdue_count += isNaN(lc) ? 0 : lc
          const la = parseFloat(cc.overdue_amount)
          this.dataCreditCompany.overdue_amount += isNaN(la) ? 0 : la
          const ld = parseFloat(cc.max_overdue_days)
          this.dataCreditCompany.max_overdue_days += isNaN(ld) ? 0 : ld
        }
        this.dataCreditCompany.loan_left = this.toDecimal2(this.dataCreditCompany.loan_left)
        this.dataCreditCompany.overdue_amount = this.toDecimal2(
          this.dataCreditCompany.overdue_amount
        )

        this.dataCreditLegal.loan_left = 0
        this.dataCreditLegal.overdue_count = 0
        this.dataCreditLegal.overdue_amount = 0
        this.dataCreditLegal.max_overdue_days = 0
        for (const cl of creditLegal) {
          const lf = parseFloat(cl.loan_left)
          this.dataCreditLegal.loan_left += isNaN(lf) ? 0 : lf
          const lc = parseFloat(cl.overdue_count)
          this.dataCreditLegal.overdue_count += isNaN(lc) ? 0 : lc
          const la = parseFloat(cl.overdue_amount)
          this.dataCreditLegal.overdue_amount += isNaN(la) ? 0 : la
          const ld = parseFloat(cl.max_overdue_days)
          this.dataCreditLegal.max_overdue_days += isNaN(ld) ? 0 : ld
        }
        this.dataCreditLegal.loan_left = this.toDecimal2(this.dataCreditLegal.loan_left)
        this.dataCreditLegal.overdue_amount = this.toDecimal2(this.dataCreditLegal.overdue_amount)

        this.dataCreditSpouse.loan_left = 0
        this.dataCreditSpouse.overdue_count = 0
        this.dataCreditSpouse.overdue_amount = 0
        this.dataCreditSpouse.max_overdue_days = 0
        for (const cs of creditSpouse) {
          const lf = parseFloat(cs.loan_left)
          this.dataCreditSpouse.loan_left += isNaN(lf) ? 0 : lf
          const lc = parseFloat(cs.overdue_count)
          this.dataCreditSpouse.overdue_count += isNaN(lc) ? 0 : lc
          const la = parseFloat(cs.overdue_amount)
          this.dataCreditSpouse.overdue_amount += isNaN(la) ? 0 : la
          const ld = parseFloat(cs.max_overdue_days)
          this.dataCreditSpouse.max_overdue_days += isNaN(ld) ? 0 : ld
        }
        this.dataCreditSpouse.loan_left = this.toDecimal2(this.dataCreditSpouse.loan_left)
        this.dataCreditSpouse.overdue_amount = this.toDecimal2(this.dataCreditSpouse.overdue_amount)
      }
    },

    // 结论
    async getLevelReport() {
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'credit_level_report', {
          index: 1,
          size: 1,
          'customer_related_id.eq': this.customer_related_id,
        })
      )
      if (res && res.data && res.data.data && res.data.data.length) {
        this.dataReportSolid = res.data.data[0]
        this.dataReport = { ...this.dataReportSolid }
        this.isAddReport = true
      } else {
        this.isAddReport = false
      }
    },

    // 评分过程
    async getLevelCustomer() {
      // this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(
          'credit',
          'credit_level_customer',
          {
            'customer_related_id.eq': this.customer_related_id,
          },
          { order_num: 'asc' }
        )
      )
      // this.loading = false
      if (res && res.data) {
        this.dataScore = []
        this.dataScoreFirstList = [] // 一类指标表格
        this.dataScoreLoseList = [] // 扣分项
        this.dataScoreGet = 0 // 得分
        this.dataScoreLose = 0 // 扣分
        const firstxAxisData = [] // 一类指标X轴
        const firstSeriesData = [] // 一类指标Y轴数据
        const secondxAxisData = [] // 二类指标X轴
        const secondSeriesData = [] // 二类指标Y轴数据
        let secondCount = 0
        for (const sd of this.dataScoreSecondList) {
          sd.count = 0
        }

        const data = this.calcSpan(res.data, 'first_level_norm_name')

        // 一类指标得分
        for (let fl of this.dataScoreFirstList) {
          fl.score = this.toDecimal2(fl.score)
          fl.percent = fl.totalScore > 0 ? fl.score / fl.totalScore : 0
          if (fl.percent >= 80) {
            fl.score_a = true
          } else if (fl.percent >= 60) {
            fl.score_b = true
          } else {
            fl.score_c = true
          }
          fl.percent = this.toDecimal2(fl.percent)
          // 一类指标图表数据
          firstxAxisData.push(fl.name)
          firstSeriesData.push(fl.percent)
        }

        for (let d of data) {
          // 指标权重
          d.norm_weight = this.toDecimal2((+d.norm_weight || 0) * 100)
          if (d.is_deductions === '0') {
            this.dataScore.push(d)
            this.dataScoreGet += +d.weight_score || 0
            // 二类指标图表数据
            secondxAxisData.push(d.second_level_norm_name.substring(0, 10))
            secondSeriesData.push(d.subject_score)

            secondCount++
            let dr = parseFloat(d.subject_score)
            dr = isNaN(dr) ? 0 : dr
            if (dr >= 80) {
              this.dataScoreSecondList[0].count++
            } else if (dr >= 60) {
              this.dataScoreSecondList[1].count++
            } else if (dr >= 30) {
              this.dataScoreSecondList[2].count++
            } else {
              this.dataScoreSecondList[3].count++
            }
          } else {
            this.dataScoreLoseList.push(d)
            this.dataScoreLose += +d.weight_score || 0
          }
        }
        this.dataScoreEmpty = this.dataScore.map(item => {
          return { ...item }
        })
        this.dataScoreLoseListEmpty = this.dataScoreLoseList.map(item => {
          return { ...item }
        })
        this.dataScoreGet = this.toDecimal2(this.dataScoreGet)
        this.dataScoreLose = this.toDecimal2(this.dataScoreLose)

        // 计算二类指标数量占比
        if (secondCount > 0) {
          for (const drd of this.dataScoreSecondList) {
            drd.percent = this.toDecimal2((drd.count / secondCount) * 100)
          }
        }

        this.optionFirst = {
          title: {
            left: 'center',
            text: '一类指标得分占比',
          },
          xAxis: {
            type: 'category',
            data: firstxAxisData,
            axisLabel: {
              interval: 0,
            },
          },
          yAxis: {
            name: '百分比',
            type: 'value',
            min: 0,
            max: 120,
            axisLabel: {
              formatter: '{value}%',
            },
          },
          series: [
            {
              data: firstSeriesData,
              type: 'line',
              label: {
                normal: {
                  show: true,
                  position: 'top',
                  formatter: '{c}%',
                },
              },
              itemStyle: {
                color: '#5b9bd5',
              },
              markLine: {
                silent: true,
                label: {
                  normal: { formatter: '{c}%' },
                },
                lineStyle: {
                  color: '#b92f30',
                  type: 'solid',
                },
                data: [
                  {
                    yAxis: 60,
                  },
                ],
              },
            },
          ],
        }

        this.optionSecond = {
          title: {
            left: 'center',
            text: '指标得分分布图',
          },
          grid: {
            bottom: '40%',
          },
          xAxis: {
            type: 'category',
            data: secondxAxisData,
            axisLabel: {
              interval: 0,
              rotate: 90,
            },
          },
          yAxis: {
            name: '得分',
            type: 'value',
            min: 0,
            max: 120,
          },
          series: [
            {
              data: secondSeriesData,
              type: 'bar',
              label: {
                normal: {
                  show: true,
                  position: 'top',
                  formatter: params => (params.value ? parseInt(params.value) : 0),
                },
              },
              itemStyle: {
                color: '#5b9bd5',
              },
              markLine: {
                silent: true,
                label: {
                  normal: { formatter: '{c}%' },
                },
                lineStyle: {
                  color: '#b92f30',
                  type: 'solid',
                },
                data: [
                  {
                    yAxis: 60,
                  },
                ],
              },
            },
          ],
        }
      } else {
        this.isAddReport = false
        return this.$message.warning('暂无评级得分数据！')
      }
    },

    // 计算合并单元格
    calcSpan(data, id) {
      const tempData = []

      const idList = []
      let tempIndex = 0
      for (let i = 0; i < data.length; i++) {
        const d = data[i]
        const v = d[id]
        d.rowspan = 1
        d.totalScore = 0

        let isFirst = true
        for (let j = 0; j < idList.length; j++) {
          if (v === idList[j]) {
            isFirst = false
            break
          }
        }

        if (isFirst) {
          tempIndex = i
          idList.push(v)
          if (d.is_deductions === '0') {
            this.dataScoreFirstList.push({
              name: d.first_level_norm_name,
              score: +d.weight_score || 0,
              totalScore: +d.norm_weight || 0,
              percent: 0,
              score_a: false,
              score_b: false,
              score_c: false,
            })
          }
        } else {
          data[tempIndex].rowspan++
          d.rowspan = 0
          // 一类指标
          if (d.is_deductions === '0') {
            const fl = this.dataScoreFirstList[this.dataScoreFirstList.length - 1]
            fl.score += +d.weight_score || 0
            fl.totalScore += +d.norm_weight || 0
          }
        }

        data[tempIndex].totalScore += parseFloat(d.norm_weight) * 100
        tempData.push(d)
      }

      return tempData
    },

    // 强制保留两位小数
    toDecimal2(x) {
      let f = parseFloat(x)
      if (isNaN(f)) {
        return '0.00'
      }
      f = Math.round(x * 100) / 100
      let s = f.toString()
      let rs = s.indexOf('.')
      if (rs < 0) {
        rs = s.length
        s += '.'
      }
      while (s.length <= rs + 2) {
        s += '0'
      }
      return s
    },

    // 保存
    onReportSave(key) {
      const data = {}
      if (this.isAddReport) {
        // 修改
        if (this.dataReportSolid[key] !== this.dataReport[key]) {
          data[key] = this.dataReport[key]
          this.apiReportUpdate(data)
        }
      } else {
        // 添加
        const value = this.dataReport[key]
        if (!value) {
          return
        }
        data.customer_id = this.dataBase.customer_id
        data.customer_related_id = this.customer_related_id
        data.rating_status = '1'
        data[key] = value
        this.apiReportAdd(data)
      }
    },
    onScoreSave(key, index, isLose) {
      let data = {}
      let tempdata = {}
      if (isLose) {
        data = this.dataScoreLoseList[index]
        tempdata = this.dataScoreLoseListEmpty[index]
        data.weight_score = data.subject_score
      } else {
        data = this.dataScore[index]
        tempdata = this.dataScoreEmpty[index]
        data.weight_score = Math.round(data.norm_weight * data.subject_score * 100) / 10000
      }

      if (data.id && data[key] !== tempdata[key]) {
        const postData = {}
        postData[key] = data[key]
        postData.weight_score = data.weight_score
        this.apiScoreUpdate(data.id, postData)
      }
    },
    async apiScoreUpdate(id, data) {
      const [res] = await this.$utils.promise(
        this.$api.updateData('credit', 'credit_level_customer', id, data)
      )
      if (res) {
        await this.getLevelCustomer()
        this.getLevelScore()
      }
    },
    async apiReportAdd(data) {
      const [res] = await this.$utils.promise(
        this.$api.addData('credit', 'credit_level_report', data)
      )
      if (res) {
        this.getLevelReport()
      }
    },
    async apiReportUpdate(data) {
      await this.$utils.promise(
        this.$api.updateData('credit', 'credit_level_report', this.dataReport.id, data)
      )
    },
    async onReportComplete() {
      if (!this.isAddReport) {
        location.href = `#banned_result`
        const ref = this.$refs[`textarea_banned_result`]
        if (ref) {
          ref.focus()
        }
        return this.$message.error('请先输入结论！')
      }
      const validMap = [
        { key: 'banned_result', message: '禁入指标结论' },
        { key: 'first_norm_result', message: '一类指标分析结论' },
        { key: 'second_norm_result', message: '二类指标分析结论' },
        { key: 'litigation_des', message: '债务涉诉情况' },
        { key: 'deduction_result', message: '银行征信情况' },
        { key: 'rating_opinion', message: '写评级意见' },
        { key: 'guarantee_opinion', message: '担保建议' },
        // {key: 'subject_score', message: '各项加权得分'}
      ]
      let valid = true
      for (const map of validMap) {
        const key = map.key
        if (!this.dataReport[key]) {
          location.href = `#${key}`
          const ref = this.$refs[`textarea_${key}`]
          if (ref) {
            ref.focus()
          }
          valid = false
          this.$message.error(`请先填写${map.message}！`)
          break
        }
      }
      if (!valid) {
        return
      }

      this.$confirm('完成报告后，结论将不能再修改, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.addLoading = true
          const [res] = await this.$utils.promise(
            this.$api.updateData('credit', 'credit_level_report', this.dataReport.id, {
              rating_status: '2',
            })
          )
          this.addLoading = false
          if (res) {
            this.$message.success('评级结果已完成')
            this.init()
          } else {
            this.$message.error('完成评级结果失败，请重试！')
          }
        })
        .catch(() => {})
    },

    printPage() {
      // 解决echarts图片打印空白问题
      const cf = this.$refs.echartsFirst
      if (cf) {
        const ef = cf.getChart()
        this.echartsFirstImg = ef ? ef.getDataURL() : ''
      }
      const cs = this.$refs.echartsSecond
      if (cs) {
        const es = cs.getChart()
        this.echartsSecondImg = es ? es.getDataURL() : ''
      }
      this.printLoading = true
      setTimeout(() => {
        this.printLoading = false
        printHtml(
          document.getElementById('report-print').innerHTML,
          `
            .report-title {text-align: center;margin-bottom: 1rem;font-weight: bold;font-size: 1.5rem;line-height: 1.5;}
            .report-section {margin-bottom: 1rem;}
            .report-section .table-bordered td {border-color: #333;padding: 0.25rem;text-align: center;vertical-align: middle;}
            .report-section-title {font-size: 1rem;font-weight: bold;}
          `
        )
      }, 300)
    },
  },

  filters: {
    textFilter(value, unit = '') {
      return value ? `${value}${unit}` : ''
    },
  },
}
</script>

<style lang="scss" scoped>
$report-width: 1000px;
$report-input-border-color: #333;

.report-action {
  width: $report-width;
  margin: 1rem auto;
}

.report-wrap {
  width: $report-width;
  margin: 0 auto;
  padding: 4rem;
  border: 1px solid #e9ecef;
  border-radius: 2px;
  background-color: #fff;
  font-family: SimSun;
  .report-title {
    text-align: center;
    margin-bottom: 1rem;
    font-weight: bold;
    font-size: 1.5rem;
    line-height: 1.5;
  }
  .report-section {
    margin-bottom: 1rem;
    .table-bordered td {
      border-color: #333;
      padding: 0.25rem;
      text-align: center;
      vertical-align: middle;
      &.report-input-last-td {
        border-right-color: $report-input-border-color;
      }
      &.report-input-td {
        border-color: $report-input-border-color;
        background-color: #ffffee;
        padding: 0;
        .form-control {
          border: none;
          background-color: #ffffee;
          padding: 0.25rem;
        }
      }
    }
  }
  .report-complete .report-input-td {
    background-color: #ffffff !important;
  }
  .report-section-title {
    font-size: 1rem;
    font-weight: bold;
  }
}
</style>
